package com.telit.firecommand.facade;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.constant.MsgIdentificationConstants;
import com.telit.common.constant.RoleCodeConstants;
import com.telit.common.core.utils.FeignUtils;
import com.telit.common.entity.DataReturn;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.JwtTokenUtils;
import com.telit.common.util.LanguageUtils;
import com.telit.communicate.dto.SendMessageDTO;
import com.telit.communicate.feign.RemoteCommunicateService;
import com.telit.firecommand.entity.FireGrowExtend;
import com.telit.upms.dto.DynamicParamsForQueryUserDto;
import com.telit.upms.feign.RemoteUpmsService;
import com.telit.upms.vo.MicroSysDistrictVo;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Component
@RequiredArgsConstructor
@Slf4j
public class FireGrowExtendTriggerFacadeService {


    private final ApplicationContext applicationContext;

    private final RemoteCommunicateService communicateFeignClient;

    private final RemoteUpmsService remoteUpmsService;


    public void pushMsg(FireGrowExtend entity) {

        pushWebSocket(JSONUtil.toJsonStr(entity));
        log.info("扩大响应开始执行socker");
    }

    @Async
    @EventListener
    @SuppressWarnings("all")
    public void pushWebSocket(String msg) {
        final TimeInterval timeInterval = DateUtil.timer();

        final FireGrowExtend fireGrowExtend = JSONUtil.toBean(msg, FireGrowExtend.class);
        if (ObjectUtil.isNull(fireGrowExtend)) {
            log.error("websocket扩大响应失败,信息解析失败:msg[{}]", msg);
            return;
        }
        //获取websocket 推送内容
        final SendMessageDTO wsDto = buildDtoForWebSocket(fireGrowExtend);
        try {
            if (ObjectUtil.isNotNull(wsDto)) {
                final DataReturn dr = communicateFeignClient.sendMsg(wsDto);
            }
        } catch (Exception e) {
            log.error("微服务内部错误：websocket扩大响应失败!msg:[{}],dr:[{}]", msg, e.getMessage());
        }
    }

    /**
     * 构造websocket 推送对象
     *
     * @return 构造的dto对象
     */
    private SendMessageDTO buildDtoForWebSocket(FireGrowExtend entity) {
//        FireTransferReportVO fireTransferReportVO = new FireTransferReportVO();
//        BeanUtils.copyProperties(entity,fireTransferReportVO);
//        fireTransferReportVO.setTransferStatusStr(TransgerReportStatus.code2Str(entity.getTransferStatus()));
        //根据转交下发流转的待处理人的行政区划code查询对应的账号id集合
        final List<Long> fireMangerIdList = CollUtil.<Long>newArrayList();
        if (entity.getDistrictCode() != null) {
            List<Long> userIds = fireMangerIdListByDistrictCode(entity.getDistrictCode());
            fireMangerIdList.addAll(userIds);
        } else {
            List<Long> userIds = new ArrayList<>();
            fireMangerIdList.addAll(userIds);
        }
        //将自己排除
        if (fireMangerIdList != null && fireMangerIdList.size() > 0) {
            Iterator<Long> iterator = fireMangerIdList.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals(JwtTokenUtils.getId())) {
                    iterator.remove();
                }
            }
        }

        if (fireMangerIdList != null && fireMangerIdList.size() > 0) {
            //构造消息体
            return new SendMessageDTO("WEBWITHINUSERID", Convert.toStrArray(fireMangerIdList),
                    JSON.toJSONString(DataReturn.ok(MsgIdentificationConstants.GROW_RESPONSE, entity)));
        } else {
            return null;
        }
    }


    //调整获取人员方式
    private List<Long> fireMangerIdListByDistrictCode(String districtCode) {
        //根据行政区划编码查询行政区划ID
        com.telit.common.core.utils.Result<Map<String, MicroSysDistrictVo>> selectDistrictDetailByListCodesResult = remoteUpmsService.selectDistrictDetailByListCodes(
                Arrays.asList(districtCode));
        Map<String, MicroSysDistrictVo> microSysDistrictVoMap = FeignUtils.unwrap(
                selectDistrictDetailByListCodesResult);
        MicroSysDistrictVo microSysDistrictVo = microSysDistrictVoMap.get(districtCode);
        if (microSysDistrictVo == null) {
            throw new ForestBaseException(LanguageUtils.codeMessage(ResultCode.OPERATE_ERROR.getCode(), districtCode));
        }

        DynamicParamsForQueryUserDto dynamicParamsForQueryUserDto = DynamicParamsForQueryUserDto.builder()
                .page(JSONUtil.toJsonStr(new Page<>(1, 1000)))
                .roleId(RoleCodeConstants.ROLE_CODE_FIRE_MANAGER_ID)//2023-01-10：由于统一平台不支持通过角色码查询，只能固定角色ID查询
                .areaId(microSysDistrictVo.getId())//行政区划Id
                .areaRecursion(false)//是否开启行政区划递归往下搜索
                .build();
        com.telit.common.core.utils.Result<Page<MicroSysUserAllInfoVo>> selectUserContainDeptAndRoleForPageSupportOrderResult = remoteUpmsService.selectUserContainDeptAndRoleForPageSupportOrder(
                dynamicParamsForQueryUserDto);
        Page<MicroSysUserAllInfoVo> microSysUserAllInfoVoPage = FeignUtils.unwrap(
                selectUserContainDeptAndRoleForPageSupportOrderResult);
        List<Long> userLists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(microSysUserAllInfoVoPage.getRecords())) {
            microSysUserAllInfoVoPage.getRecords().stream()
                    .forEach(microSysUserAllInfoVo -> {
                        userLists.add(microSysUserAllInfoVo.getId());
                    });
        }
        return userLists;
    }
}
